'use strict';
const db = uniCloud.database()
exports.main = async (event, context) => {
	let res=null
	if(event.action=="getVideoInfo"){
		let {url}=event.params
		let regex = "(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]"
		url=url.match(regex)[0];
		if(url.indexOf("douyin")!=-1){
			res=await uniCloud.httpclient.request(url,{method:"GET",dataType: 'text'})
			//视频获取mid
			let mid=res.headers.location.split("/")[5]
			//通过mid获取视频详情
			let body= await uniCloud.httpclient.request("https://www.iesdouyin.com/web/api/v2/aweme/iteminfo/?item_ids="+mid,{dataType: 'text'});
			body=JSON.parse(body.data)
			//初始化视频信息 
			res={desc:body.item_list[0].desc,video:body.item_list[0].video.play_addr.url_list[0].replace("playwm","play"),
				image:body.item_list[0].video.origin_cover.url_list[0],
				music:body.item_list[0].music.play_url.url_list[0]
			}
			//把视频地址转换成无水印的
			let temp=await uniCloud.httpclient.request(
			res.video,{method:"GET",
			dataType: 'text'})
			res.video=temp.headers.location
			//打印视频结果
			console.log(res)
			return res
		}else if(url.indexOf("kuaishou")!=-1){
			let headers={"User-Agent": "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Mobile Safari/537.36"};
			res=await uniCloud.httpclient.request(url,{method:"GET",headers,dataType: 'text'})
			console.log(res)
			//视频获取mid
			let redirectUrl=res.headers.location
			let body=await uniCloud.httpclient.request(redirectUrl,{method:"GET",headers,dataType: 'text'})
			let info=JSON.parse(body.data.split("script\">")[4].split("</script>")[0].replace("window.pageData= ",""))
			console.log(info)
			res={
				desc:info.video.caption,
				video:info.video.srcNoMark.substr(0,info.video.srcNoMark.indexOf("?")),
				image:info.video.shareCover,
				user:info.video.user
			}
		}
	}
	
    return res
};
